package javamobile.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybeans.dao.DAOException;

import javamobile.model.*;

public class ClosedBillListAction extends Action{

	private DAOFactory factory;
	
	public ClosedBillListAction(Model model) {
		factory = model.getDAOFactory();
	}
	
	@Override
	public String getName() {return "closed.do";}

	@Override
	public Map<String, Object> perform(Map<String, Object> input) {
		System.out.println("Performing closedbill action!");
		Map<String, Object> output = new HashMap<String, Object>();
		List<String> errors = new ArrayList<String>();
		output.put("errors", errors);
		
		String username = (String) input.get("username");

		try {
			User user = factory.lookupUser(username);
			if (user == null) {
            errors.add("User "+username+" not found");
            return output;
			}

            List<Bill> openBillList = factory.getClosedBillList(user.getUserID());
            List<ExtendedBill> extendedBill = new ArrayList<ExtendedBill> ();
            for (int i=0; i<openBillList.size();  i++) {
        		Bill b = openBillList.get(i);
        		ExtendedBill eb = new ExtendedBill 
        				(b.getCreaterID(), b.getPayerID(), b.getAmount(), b.getDate(), b.getDescription(), b.getState(), b.getNextNotificationDate(), b.getLocation());
        		User u = factory.lookupUser(b.getCreaterID());
        		eb.setCreaterName(u.getFirstName()+" "+u.getLastName());
        		eb.setBillID(b.getBillID());
        		extendedBill.add(eb);
        	}
            List<String> names = new ArrayList<String> ();
            List<Double> amounts = new ArrayList<Double> ();
            List<String> dates = new ArrayList<String> ();
            List<Integer> billIDs = new ArrayList<Integer> ();
            for (ExtendedBill eb:extendedBill) {
            	names.add(eb.getCreaterName());
            	amounts.add(eb.getAmount());
            	dates.add(eb.getDate());
            	billIDs.add(eb.getBillID());
            }
            output.put("names", names);
            output.put("amounts", amounts);
            output.put("dates", dates);
            output.put("billIDs", billIDs);
        }
		catch (DAOException e) {
        	errors.add(e.getMessage());
        	return output;
	    }

		return output;
	}

}